package com.houzehui.cart.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.houzehui.cart.api.ProductFiegn;
import com.houzehui.cart.api.StockFiegn;
import com.houzehui.cart.service.CartService;
import com.houzehui.cart.vo.CartVo;
import com.houzehui.cart.vo.ProductVo;
import com.houzehui.common.vo.SkuVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class CartServiceImpl implements CartService {


    @Resource
    RedisTemplate redisTemplate;
    private String cartKey="myCart:%s";



    @Resource
    ProductFiegn productFiegn;
    @Resource
    StockFiegn stockFiegn;

    @Override
    public Boolean add(Long userId,Long skuId,Long number) {

        String key=String.format(cartKey,userId);

        redisTemplate.opsForHash().put(key,skuId,number);

        return true;
    }

    @Override
    public CartVo myCart(Long userId) {
        //返回购物车信息
        CartVo cartVo = new CartVo();
        //赋值用户Id
        cartVo.setUserId(userId);

        String key=String.format(cartKey,userId);
        //获取购物车的所有数据
        HashMap entries = (HashMap) redisTemplate.opsForHash().entries(key);
        //取出所有的key
        Set set = entries.keySet();
        List<Long> skuIdList = new ArrayList<>(set);

        //调用商品服务 查询商品信息
        List<SkuVo> SkuVoList = productFiegn.getBySkuIds(skuIdList);

        //封装购物车 的商品列表
        List<ProductVo> ProductVoList = new ArrayList<>();

        AtomicLong total= new AtomicLong();
        SkuVoList.forEach(skuVo->{

            ProductVo productVo = new ProductVo();
            BeanUtil.copyProperties(skuVo,productVo);
            productVo.setNumber((Long) entries.get(productVo.getId()));
            productVo.setTotal(productVo.getNumber()*productVo.getPrice());

            total.addAndGet(productVo.getTotal());
        });

        //赋值总价
        cartVo.setTotal(total.get());

        return cartVo;
    }




    @Override
    public Boolean delete(Long userId,Long skuId) {

        String key=String.format(cartKey,userId);

        redisTemplate.opsForHash().delete(key,skuId);
        return null;
    }
}
